<template>
  <div>
    <el-form
        :inline="true"
        :model="formInline"
        class="demo-form-inline"
        style="margin-top: 0px; line-height: 10px;margin-left: 25px"
    >
      <el-form-item label="账单人姓名">
        <el-select
            v-model="formInline.patient_name"
            placeholder="账单人"
            clearable
        >
          <el-option
              v-for="patient in tableData"
              :key="patient.patient_name"
              :lable="patient.patient_name"
              :value="patient.patient_name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="清单状态">
        <el-select v-model="formInline.status" clearable placeholder="状态">
          <el-option lable="正在处理" value="正在处理"></el-option>
          <el-option
              lable="诊断完成，待缴费"
              value="诊断完成，待缴费"
          ></el-option>
          <el-option lable="已缴费" value="已缴费"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="select">查询</el-button>

        <el-button type="danger" plain @click="resetForm"
        >重置
        </el-button
        >
      </el-form-item
      >
    </el-form>
    <el-card class="box-card-record" style="margin-left: 25px">
      <el-table
          :data="tableData"
          style="width: 100%;margin-bottom: 20px;"
          row-key="id"
          border
          lazy
          :tree-props="{children: 'medicine_list', hasChildren: 'hasChildren'}">
        <el-table-column prop="id" label="ID" width="100" sortable></el-table-column>
        <el-table-column prop="patient_name" width="120" label="姓名"></el-table-column>
        <el-table-column prop="mobile" width="120" label="联系电话"></el-table-column>
        <el-table-column prop="doctor_name" width="120" label="开单医生"></el-table-column>
        <el-table-column prop="medicine_name" width="120" label="药品名称"></el-table-column>
        <el-table-column prop="medicine_price" width="120" label="药品单价"></el-table-column>
        <el-table-column prop="medicine_category" width="120" label="药品类型"></el-table-column>
        <el-table-column prop="careful_note" width="120" label="注意事项"></el-table-column>
        <el-table-column prop="total_price" width="120" label="清单总价"></el-table-column>
        <el-table-column prop="status_name" width="120" label="清单状态">
          <template slot-scope="scope">
            <el-tag type="danger" v-if="scope.row.status_name === '未缴费'" effect="dark">未缴费</el-tag>
            <el-tag type="primary" v-if="scope.row.status_name === '缴费中'" effect="dark">缴费中</el-tag>
            <el-tag type="success" v-if="scope.row.status_name === '已缴费'" effect="dark">已缴费</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="确认并缴费/删除清单">
          <template slot-scope="scope" v-if="scope.row.patient_name">
            <el-button
                el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="confirmInformation(scope.row),(drawer = true)"
                size="small"
                v-if="scope.row.status_name !== '已缴费'"
            ></el-button>
            <!--                v-if="user_type === '管理员'"-->
            <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="deteleSingle(scope.row)"
                size="small"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-pagination
        background
        layout="prev, pager, next,total"
        :total=departmentPageDto
        :page-size=filter.size
        :current-page.sync="currentPage"
        style="margin-left: 600px; margin-top: 30px"
        @current-change="handleCurrentChange"
    >
    </el-pagination>
    <el-dialog title="确认账单信息" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="账单ID" :label-width="formLabelWidth">
          <el-input v-model="form.id" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="账单人姓名" :label-width="formLabelWidth">
          <el-input v-model="form.patient_name" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth">
          <el-input v-model="form.mobile" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="药品信息" :label-width="formLabelWidth">
          <el-popover
              placement="right"
              width="400"
              trigger="click">
            <el-table :data="gridData">
              <el-table-column width="100" property="id" label="ID"></el-table-column>
              <el-table-column width="150" property="medicine_name" label="名称"></el-table-column>
              <el-table-column width="100" property="medicine_price" label="单价"></el-table-column>
              <el-table-column width="300" property="medicine_category" label="类型"></el-table-column>
            </el-table>
            <el-button slot="reference">查看药单</el-button>
          </el-popover>
        </el-form-item>
        <el-form-item label="清单总价" :label-width="formLabelWidth">
          <el-input v-model="form.price" autocomplete="off" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="pay(form.price, form.patient_name)">去缴费</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      result: {},
      currentPage: null,
      tableData: [{}],
      user: {},
      formInline: {
        deptCategoryName: "",
        status: "",
        patient_name: "",
      },
      filter: {
        size: 5,       // 单页数据量
        page: 1,
      },
      departmentClassification: [],
      pageTotal: "",
      departmentPageDto: null,
      form: {
        id: '',
        patient_name: '',
        mobile: '',
        price: '',
        medicine: '',
        doctor_name: '',
      },
      dialogFormVisible: false,
      formLabelWidth: '120px',
      gridData: [],
      user_type: '',
    };
  },
  created() {
    this.user_type = this.$getSessionStorage('user_type')
    this.user = this.$getSessionStorage("user");
    //this.patientRegister();
    // this.selectDepartmentClassification();
    this.paging(1);
    // 获取清单信息
    this.$axios.get(`${this.$settings.BASE_URL}` + 'registered/list_detail/').then(res => {
      this.tableData = res.data.results
      this.departmentPageDto = res.data.count;
    })

    // url后拼接的参数：?及后面的所有参数 => ?a=1&b=2
    // console.log(location.search);

    // 解析支付宝回调的url参数
    let params = location.search.substring(1);  // 去除? => a=1&b=2
    let items = params.length ? params.split('&') : [];  // ['a=1', 'b=2']
    //逐个将每一项添加到args对象中
    for (let i = 0; i < items.length; i++) {  // 第一次循环a=1，第二次b=2
      let k_v = items[i].split('=');  // ['a', '1']
      //解码操作，因为查询字符串经过编码的
      if (k_v.length >= 2) {
        // url编码反解
        let k = decodeURIComponent(k_v[0]);
        this.result[k] = decodeURIComponent(k_v[1]);
        // 没有url编码反解
        // this.result[k_v[0]] = k_v[1];
      }

    }
    // 解析后的结果
    // console.log(this.result);
    // console.log(location.search)
    // // 把地址栏上面的支付结果，再get请求转发给后端
    // this.$axios({
    //   url: this.$settings.BASE_URL + 'order/success/' + location.search,
    //   method: 'get',
    // }).then(response => {
    //   if (response.data.code != 100) {
    //     this.$message('暂时未收到您的付款，请稍后刷新再试')
    //   }
    // }).catch(() => {
    //   console.log('支付结果同步失败');
    // })

  },
  methods: {
    confirmInformation(row) {
      this.dialogFormVisible = true
      this.form.id = row.id
      this.form.patient_name = row.patient_name
      this.form.mobile = row.mobile
      this.form.price = row.price + '￥'
      this.form.doctor_name = row.doctor_name
      this.gridData = row.medicine_list
    },
    deteleSingle(row) {
      console.log(row.id)
      this.$confirm("确认要删除吗？")
          .then((_) => {
            this.$axios.delete(this.$settings.BASE_URL + `registered/list_detail/${row.id}/`).then(response => {
              this.$message({
                message: `已删除清单${row.id}`,
                type: 'success',
                duration: 1000
              })
              window.location.reload()
            })
          })
          .catch((_) => {

          });
    },
    resetForm() {
      location.reload();
    },
    select(pageNum) {
      var statusResult = this.formInline.status;
      if (statusResult.indexOf("已缴费") >= 0) {
        statusResult = "3";
      } else if (statusResult.indexOf("诊断完成，待缴费") >= 0) {
        statusResult = "1"
      } else if (statusResult.indexOf("正在处理") >= 0) {
        statusResult = "2"
      }
      //axios查询科室列表请求((分页有参))
      var a = isNaN(pageNum);
      console.log(a);
      if (isNaN(pageNum) === true) {
        pageNum = 1;
      }
      // ?doctor=${this.formInline.doctor}&department=${this.formInline.department}
      this.filter.page = pageNum
      this.$axios.get(`${this.$settings.BASE_URL}registered/list_detail/?patient_name=${this.formInline.patient_name}&status=${statusResult}`, {
        params: this.filter,
      })
          .then((Response) => {
            this.tableData = Response.data.results;
            this.departmentPageDto = Response.data.count;
            if (isNaN(pageNum) === true) {
              pageNum = 1;
            }
            this.currentPage = pageNum
          })
          .catch((error) => {
            console.error(error);
          });
    },

    paging(pageNum) {
      this.$axios
          .get(`${this.$settings.BASE_URL}registered/list_detail/`, {
            params: this.filter,
          })
          .then((res) => {
            this.tableData = res.data.results
            this.departmentPageDto = res.data.count;
          })
          .catch((error) => {
            console.error(error);
          });
    },
    handleCurrentChange(pageNumber) {
      this.select(pageNumber);
    },
    pay(price, patient_name) {
      console.log(this.gridData)
      let medicine = []
      for (let dict of this.gridData) {
        medicine.push(dict.id)
      }
      this.$axios.post(`${this.$settings.BASE_URL}registered/modify_state/`, {
        'id': this.form.id,
        'status': 2
      })
      //     .then(response => {
      //   window.location.reload()
      // })
      this.$axios.post(`${this.$settings.BASE_URL}order/alipay/`, {
        medicines: medicine,
        total_amount: price.substr(0, price.length - 1),
        subject: patient_name,
        pay_type: 1
      }).then(response => {
        if (response.data.code === 100) {
          open(response.data.pay_url, '_self')
        } else {
          this.$message({
            message: response.data.msg,
            type: 'warning',
            duration: 1000
          })
        }
      })
      this.$axios.post(`${this.$settings.BASE_URL}order/success/${location.search}`).then(res => {
        if (res.data.code != 100) {
          this.$message({
            message: res.data.msg,
            type: 'warning'
          })
        }
      })
      if (this.result){
        this.$axios.post(`${this.$settings.BASE_URL}registered/modify_state/`, {
        'id': this.form.id,
        'status': 3
      })
      }

      // window.location.reload()
    }
  },
};
</script>

<style>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card-record {
  margin-top: 0px;
  width: 1500px;
}

.transition-box {
  margin-bottom: 10px;
  width: 200px;
  height: 100px;
  border-radius: 4px;
  background-color: #409EFF;
  text-align: center;
  color: #fff;
  padding: 40px 20px;
  box-sizing: border-box;
  margin-right: 20px;
}
</style>